import {initVmSync} from "./utils.js";
import axios from "axios";
import {HttpProxyAgent} from "http-proxy-agent";
import {HttpsProxyAgent} from "https-proxy-agent";
import fs from "fs";
import workerpool from "workerpool";
import {Mutex} from "async-mutex";
// 设置 HTTP 代理
// const httpDispatcher = new ProxyAgent({uri: "http://127.0.0.1:7890"});
//
// setGlobalDispatcher(httpDispatcher);


let config = {
    domUrl: 'https://www.google.com/travel/flights/booking?tfs=CBwQAhpJEgoyMDI0LTExLTA2Ih8KA0hLRxIKMjAyNC0xMS0wNhoDTlJUKgJIQjIDMzIwagwIAhIIL20vMDNoNjRyDAgCEggvbS8wN2RmaxpJEgoyMDI0LTExLTIwIh8KA05SVBIKMjAyNC0xMS0yMBoDSEtHKgJIQjIDMzIzagwIAhIIL20vMDdkZmtyDAgCEggvbS8wM2g2NEABSAFwAYIBCwj___________8BmAEB&tfu=CmxDalJJZDFWaVpURnpjbFZxUkc5QlRteFpNMmRDUnkwdExTMHRMUzB0TFhSaVluZHdORUZCUVVGQlIyTlhUMDF6UVdGMk5tZEJFZ1ZJUWpNeU14b0tDSUlQRUFBYUEwaExSRGdjY0piQkFRPT0SBggAIAEoCCIA&hl=en&gl=HK',
    script_name: 'https://www.gstatic.com/',
    debug: false,
    proxy: false,
    keepRandom: false,
    body: '',
    cookie: undefined,
    cookie2: undefined,

    type: 'ksada'


}

async function getData() {
    function randomSessionId() {
        let strs = 'abcdefghijklmnopqrstuvwxyz1234567890';
        let sessionID = '';
        for (let i = 0; i < 8; i++) {
            sessionID += strs.charAt(parseInt(Math.random() * strs.length))
        }
        return sessionID;
    }

    let uri = "https://www.google.com/travel/flights/search"

    let params = {
        "tfs": "CBwQAhojEgoyMDI1LTAyLTEwagcIARIDTEFYcgwIAxIIL20vMDFfZDRAAUgBcAGCAQsI____________AZgBAg",
        "tfu": "EgIIACIA",
        "gl": "US"
    }
    let proxy = {
        "password": "WPxpuBFj", "server": "10.188.200.27:31502",
        // "password": "5L79ZAew", "server": "43.135.155.176:8891",
        // "password": "5L79ZAew", "server": "localhost:7890",
        "username": "userID-734-orderid-9670-region-us-sessionID-11111-sessiontime-5"
    }
    let users = proxy.username.split('-')
    let sessIdIdx = users.indexOf('sessionID') + 1;
    users[sessIdIdx] = randomSessionId();
    proxy.username = users.join('-')
    const httpAgent = new HttpProxyAgent(`http://${proxy.username}:${proxy.password}@${proxy.server}`, {
        timeout: 9000,
    });
    const httpsAgent = new HttpsProxyAgent(`http://${proxy.username}:${proxy.password}@${proxy.server}`, {
        timeout: 9000,
    });
    proxy = {
        host: proxy.server.split(':')[0],
        port: parseInt(proxy.server.split(':')[1]), // 如果你的代理服务器需要认证，则还需要添加：
        auth: {
            username: users.join('-'),
            password: proxy.password
        },
        protocol: 'http'
    }
    let client = axios.create({
        timeout: 9000,
        maxBodyLength: 1024 * 1024 * 1024 * 1024,
        httpAgent: httpAgent,
        httpsAgent: httpsAgent
        // proxy: proxy
    });
    let r = await client.request({
        url: uri,
        params: params
        ,
        headers: {
            "Host": "www.google.com",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "priority": "u=0, i",
            "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
            "sec-ch-ua-arch": "\"arm\"",
            "sec-ch-ua-bitness": "\"64\"",
            "sec-ch-ua-form-factors": "\"Desktop\"",
            "sec-ch-ua-full-version": "\"131.0.6778.70\"",
            "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"131.0.6778.70\", \"Chromium\";v=\"131.0.6778.70\", \"Not_A Brand\";v=\"24.0.0.0\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-model": "\"\"",
            "sec-ch-ua-platform": "\"macOS\"",
            "sec-ch-ua-platform-version": "\"15.1.0\"",
            "sec-ch-ua-wow64": "?0",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "x-browser-channel": "stable",
            "x-browser-copyright": "Copyright 2024 Google LLC. All rights reserved.",
            "x-browser-validation": "f17l9rSuHmrgo31qEeG2bl8fxeI=",
            "x-browser-year": "2024"
        }
    })


    // 假设 text 是输入的字符串
    const text = r.data.toString('utf-8')
    // fs.writeFileSync('./jsinfo.txt', text, {
    //     encoding: 'utf-8'
    // })
// 正则匹配提取 mnsUbf 的值
    const mnsUbf = text.match(/mnsUbf":"(.+?)","nQyAE/)[1];

// 处理字符串
    let data = '[' + mnsUbf.slice(4);

// 处理 unicode-escape 解码
    data = Buffer.from(data).toString('utf-8'); // 自动处理 unicode 转义
    let d1 = data.replace(/\\?\\u(\w{4})/g, (a, b) => String.fromCharCode(parseInt(b, 16)));

// 如果遇到需要特殊处理的 unicode 字符（如 \uXXXX 格式）
// 可以用以下方式强制解码：
    data = JSON.parse(d1.replaceAll('\\"', '"').replaceAll('\\\\"', '\\"'))


    let long_str = data[0]
    let func = data[5][5]
    return {
        'func': func.split('\\n').slice(1,).join('\\n')
            .replaceAll(',\\n', ',')
            // .replaceAll('\\\\n','\\n')
            .replaceAll('\\\\', '\\'),
        'long_str': long_str
    }
}
let uuid = Math.random().toString(36).substr(2, 9);
let sign = null;
let context = null;
let signCount = 0;
let hashId = Math.random().toString(16).slice(2,10);
async function init() {
    let res = await axios.get('http://43.135.155.176:8081/src')
    // let res = await axios.get('http://127.0.0.1:8081/src')
    res = res.data

    // let res = await getData();
    let userCode = `

    ` + res.func + `;;

    var wwwb = "${res.long_str}";;

    const c = new window.ridgeslice.gc(wwwb);
window.sign = c;`
    let html = `<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Document</title>
</head>
<body>

</body>
</html>`

    // fs.writeFile('./gfl1.js', userCode, (err)=>[
    //     console.log('err', err)
    // ])
    let {vm, context:ctx} = initVmSync(userCode, config, html)
    sign = ctx.sign;
    context =  ctx;

}
const mutex = new Mutex();

async function genSign(msg) {
    let hasReload = false;
    let beforeCount = 0;
    if (sign == null || signCount > 100) {
        sign = null;
        // if (signCount > 100){
        //     process.exit(-1)
        // }
        const release = await mutex.acquire();
        try {
            let r = await init();
            hasReload=true;
            beforeCount = signCount;
            signCount = 0;
            console.log('reload success')
        } finally {
            release(); // 释放锁
        }
    }
    if (sign !== null) {
        let d = Date.now();
        // if (signCount % 10 === 0){
        //     sign = context.window.ridgeslice.gc(context.window.wwwb)
        // }
        let res = new Promise((e, r) => {
            sign.ply(e, !0, Object.fromEntries([['mgGpzd', msg]]))
        });
        let p = await res;
        let resSign = JSON.stringify([
            p,
            null, null,
            parseInt(Math.random() * 5) + 3,
            null, null, null, 0, '5'
        ])
        signCount++;
        return {
            args: msg,
            sign: resSign,
            success:true,
            signCount,
            beforeCount,
            hasReload,
            hashId,
        }
    } else {
        return {
            args: msg,
            sign: '',
            success:false,
            signCount,
            beforeCount,
            hasReload,
            hashId
        }
    }
}

// process.on('message', async function(msg){
//     // console.log('inner message', msg);
//     if (msg.type === 'init') {
//         try {
//             let r = await init()
//             process.send('initok');
//         }catch (e){
//             process.send('initerror');
//
//         }
//
//
//     }else{
//         let d = Date.now();
//         let res = new Promise((e, r) => {
//             // console.log()
//             sign.ply(e, !0, Object.fromEntries([['mgGpzd', msg.args]]))
//         });
//         let p = await res;
//         let resSign = JSON.stringify([
//             p,
//             null,null,
//             Date.now() - d,
//             null,null,null,0,'5'
//         ])
//         process.send({
//             args: msg.args,
//             sign: resSign
//         })
//     }
// })


// init()

function asyncTimeout() {
    var me = this;
    return new Promise(function (resolve) {
        let timeout = setTimeout(() => {
            resolve();
        }, 5000);

        // 注册一个监听器，它将在上面的超时触发之前解决。
        me.worker.addAbortListener(async function () {
            clearTimeout(timeout);
            resolve();
        });
    });
}


workerpool.worker(
    {
        genSign: genSign,
    },
    {
        abortListenerTimeout: 1000
    }
);

